package com.hmall.common.config;

import com.hmall.common.utils.UserContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用MVC配置类，用于配置用户信息拦截器
 * 各个微服务可以直接使用这个配置类来处理网关传递的用户信息
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                // 从请求头获取用户ID
                String userInfo = request.getHeader("user-info");
                System.out.println("=== 拦截器调试信息 ===");
                System.out.println("请求路径: " + request.getRequestURI());
                System.out.println("user-info 请求头: " + userInfo);
                
                // 存入ThreadLocal
                if (userInfo != null) {
                    UserContext.setUser(Long.valueOf(userInfo));
                    System.out.println("已将用户ID存入ThreadLocal: " + userInfo);
                } else {
                    System.out.println("user-info 请求头为空");
                }
                System.out.println("==================");
                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                // 清理ThreadLocal
                UserContext.removeUser();
                System.out.println("已清理ThreadLocal中的用户信息");
            }
        });
    }
} 